<template>
  <div>
    <el-dialog
      v-model="props.isShow"
      :title="props.isAdd ? '添加' : '编辑'"
      center
      :before-close="cancel"
    >
      <el-form ref="specsRef" :model="specsForm" :rules="rules">
        <el-form-item label="规格名称" :label-width="formLabelWidth" prop="specsname">
          <el-input autocomplete="off" v-model="specsForm.specsname" />
        </el-form-item>
        <el-form-item
          label="规格属性"
          :label-width="formLabelWidth"
          v-for="(domain, index) in dynamicValidateForm.domains"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
        >
          <el-input v-model="domain.value" class="left" />
          <el-button @click="addDomain" v-if="index == 0">添加</el-button>
          <el-button class="mt-2" @click.prevent="removeDomain(domain)" v-else
            >删除</el-button
          >
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="specsForm.status"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"
              :active-value="1"
              :inactive-value="2"
            />
          </el-tooltip>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(specsRef)">取消</el-button>
          <el-button type="primary" @click="confirm(specsRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { defineProps, defineEmits } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { specsadd, specsinfo, specsedit } from "../../request/api";
import { useStore } from "vuex";

const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const value = ref("1");
const store = useStore();

// 双向数据绑定的值
let specsForm = ref({
  specsname: "", //商品规格名称
  attrs: "", //商品规格属性值
  status: 1, // 状态1正常2禁用
});

//定义 rules规则
let rules = reactive<FormRules>({
  specsname: [
    { required: true, message: "请输入规格名称", trigger: "blur" },
    { min: 2, max: 6, message: "长度在2-6个字符", trigger: "blur" },
  ],
});

// 用于添加的表单属性
const dynamicValidateForm = reactive<{
  domains: DomainItem[];
  email: string;
}>({
  domains: [
    {
      key: 1,
      value: "",
    },
  ],
  email: "",
});
interface DomainItem {
  key: number;
  value: string;
}

// 父子传参接受的值
let props = defineProps({
  isShow: Boolean,
  isAdd: Boolean,
});

let emit = defineEmits(["cancel"]);
let specsRef = ref<FormInstance>();
// 封装取消事件
let cancel = (formEl?: FormInstance | undefined) => {
  emit("cancel");

  specsForm.value = {
    specsname: "", //商品规格名称
    attrs: "", //商品规格属性值
    status: 1, // 状态1正常2禁用
  };
  // 让新增规格属性为空
  dynamicValidateForm.domains = [
    {
      key: 1,
      value: "",
    },
  ];

  if (!formEl) return;

  // 清除规则验证
  specsRef.value.resetFields();
};

// 删除规格属性
const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
  }
};
// 新增规格属性
const addDomain = () => {
  if (dynamicValidateForm.domains.length > 5) {
    ElMessage({
      message: "不能再多了",
      type: "error",
    });
    return;
  }
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: "",
  });
};

// 数据回显
const lookup = async (id: number) => {
  let result: any = await specsinfo({ id });
  console.log(result);
  if (result.code == 200) {
    specsForm.value = result.list[0];
    // 修改的时候需要id
    specsForm.value.id = id;
    // console.log(specsForm.value.id);
    
    // 新增规格属性回显数据
    specsForm.value.attrs.map((item: any, index: any) => {
      // console.log(item);
      if (index == 0) {
        dynamicValidateForm.domains[0].value = item;
      } else {
        dynamicValidateForm.domains.push({
          value: item,
          key: 1,
        });
      }
    });
  }
};

// 添加和编辑
const confirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((val) => {
    if (val) {
        let a = dynamicValidateForm.domains.map((v) => v.value).join(",");
        // console.log(a);
        specsForm.value.attrs = a;
      if (props.isAdd) {
        // 添加
        // console.log();
        
        specsadd(specsForm.value).then((res) => {
          if (res.code == 200) {
            // console.log(res);
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "success",
            });
            cancel();
          } else {
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
          store.dispatch("specs/getSpecsActions");
        });
      } else {
        // 编辑
        console.log(specsForm.value);
        
        specsedit(specsForm.value).then((res) => {
          if (res.code == 200) {
            // console.log(res);
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "success",
            });
            cancel();
          } else {
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
          store.dispatch("specs/getSpecsActions");
        });
      }
    }
  });
};

// 可以通过defineExpose 编译器宏来显示指定在 <script setup> 组件中要暴露出去的属性
defineExpose({
  lookup,
});
</script>

<style lang="less" scoped>
.left {
  width: 80%;
}
</style>
